package com.fucheng.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.Collections;
import java.util.List;

/**
 * 使用 Zookeeper 实现的服务发现功能
 */
public class ZookeeperServiceDiscovery implements ServiceDiscovery {

    // 服务的根结点
    private static final String ROOT_PATH = "/rpc";

    private final CuratorFramework client;

    public ZookeeperServiceDiscovery() {
        this.client = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")             // ZK 连接地址
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("registry")                      // 命名空间需与注册端一致
                .build();
        client.start();
    }

    /**
     * 从 Zookeeper 查找服务，获取所有子节点（即所有服务地址）
     */
    public List<String> getServices(String serviceName) {

        try {
            String path = ROOT_PATH + "/" + serviceName;
            return client.getChildren().forPath(path);
        } catch (Exception e) {
            System.err.println("[ZK] 服务发现失败：" + serviceName + ", " + e.getMessage());
            return Collections.emptyList();
        }
    }
}
